package cn.echo.consul.manager.util;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * 日期处理类
 * 定义DateTimeFormatter（线程安全） 替代 SimpleDateFormatter
 * @author lonyee
 */
public class DateUtil {

    static final String dateTimePattern = "yyyy-MM-dd HH:mm:ss";

    /**
     * 格式化日期时间
     */
    public static String formatDate(Date date) {
        return formatDate(date, dateTimePattern);
    }

    /**
     * 格式化日期时间
     */
    public static String formatDate(Date date, String pattern) {
        LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        return formatDate(localDateTime, pattern);
    }

    /**
     * 格式化日期时间
     */
    public static String formatDate(LocalDateTime date, String pattern) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        return dateTimeFormatter.format(date);
    }

    /**
     * 转换日期时间
     */
    public static LocalDateTime parseDate(String strDate, String pattern) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        return LocalDateTime.parse(strDate, dateTimeFormatter);
    }

    /**
     * LocalDate转换Date
     */
    public static Date asDate(LocalDate localDate) {
        return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * LocalDateTime转换Date
     */
    public static Date asDate(LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * Date转换LocalDate
     */
    public static LocalDate asLocalDate(Date date) {
        return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
    }

    /**
     * Date转换LocalDateTime
     */
    public static LocalDateTime asLocalDateTime(Date date) {
        return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
    }
}
